﻿//
// (C) Copyright 2009 Irantha Suwandarathna (iranthas@hotmail.com)
// All rights reserved.
//

/* Copyright (c) 2001-2008, The HSQL Development Group
 * All rights reserved.
 *
 * Redistribution and use _in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions _in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer _in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the HSQL Development Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EffiProz.Core.Persist;
using EffiProz.Core.DataTypes;
using EffiProz.Core.Indexes;
using EffiProz.Core.Lib;
using EffiProz.Core.Errors;
using EffiProz.Core.Navigators;

namespace EffiProz.Core
{
    public class TableBase
    {
        // types of table
        public const int SYSTEM_TABLE = 0;
        public const int SYSTEM_SUBQUERY = 1;
        public const int TEMP_TABLE = 2;
        public const int MEMORY_TABLE = 3;
        public const int CACHED_TABLE = 4;
        public const int TEMP_TEXT_TABLE = 5;
        public const int TEXT_TABLE = 6;
        public const int VIEW_TABLE = 7;
        public const int RESULT_TABLE = 8;
        public const int TRANSITION_TABLE = 9;
        public const int FUNCTION_TABLE = 10;

        //
        public const int SCOPE_STATEMENT = 11;
        public const int SCOPE_TRANSACTION = 12;
        public const int SCOPE_SESSION = 13;
        public const int SCOPE_FULL = 14;

        //
        public const int COLUMNS_UNREFERENCED = 15;
        public const int COLUMNS_REFERENCED = 16;

        //
        public PersistentStore store;
        public int persistenceScope;
        public long persistenceId;

        // columns in table
        public int[] primaryKeyCols;                      // column numbers for primary key
        public SqlType[] primaryKeyTypes;
        public int[] primaryKeyColsSequence;              // {0,1,2,...}

        //
        //
        public Index[] indexList;                  // first index is the primary key index
        public Database database;
        public int[] bestRowIdentifierCols;      // column set for best index
        public bool bestRowIdentifierStrict;    // true if it has no nullable column
        public int[] bestIndexForColumn;         // index of the 'best' index for each column
        public Index bestIndex;                  // the best index overall - null if there is no user-defined index
        public Index fullIndex;                    // index on all columns
        public bool[] colNotNull;                   // nullability
        public SqlType[] colTypes;                     // types of columns
        public int columnCount;

        //
        public int tableType;
        protected bool _isReadOnly;
        protected bool _isTemp;
        protected bool _isCached;
        protected bool _isText;
        public bool _isView;
        public bool isSessionBased;
        protected bool _isSchemaBased;
        public bool isLogged;
        private bool _isTransactional = true;
        public bool hasLobColumn;

        //
        public TableBase() { }

        //
        public TableBase(Session session, Database database, int scope, int type,
                         SqlType[] colTypes)
        {

            tableType = type;
            persistenceScope = scope;
            isSessionBased = true;
            persistenceId = database.persistentStoreCollection.getNextId();
            this.database = database;
            this.colTypes = colTypes;
            columnCount = colTypes.Length;
            primaryKeyCols = new int[] { };
            primaryKeyTypes = new SqlType[] { };
            indexList = new Index[0];

            createPrimaryIndex(primaryKeyCols, primaryKeyTypes, null);
        }

        public TableBase duplicate()
        {

            TableBase copy = new TableBase();

            copy.tableType = tableType;
            copy.persistenceScope = persistenceScope;
            copy.isSessionBased = isSessionBased;
            copy.persistenceId = database.persistentStoreCollection.getNextId();
            copy.database = database;
            copy.colTypes = colTypes;
            copy.columnCount = colTypes.Length;
            copy.primaryKeyCols = primaryKeyCols;
            copy.primaryKeyTypes = primaryKeyTypes;
            copy.indexList = indexList;

            return copy;
        }

        public int getTableType()
        {
            return tableType;
        }

        public long getPersistenceId()
        {
            return persistenceId;
        }

        public virtual int getId()
        {
            return 0;
        }

        public bool onCommitPreserve()
        {
            return persistenceScope == TableBase.SCOPE_SESSION;
        }

        public RowIterator rowIterator(Session session)
        {

            PersistentStore store = session.sessionData.getRowStore(this);

            return getPrimaryIndex().firstRow(store);
        }

        public RowIterator rowIterator(PersistentStore store)
        {
            return getPrimaryIndex().firstRow(store);
        }

        public int getIndexCount()
        {
            return indexList.Length;
        }

        public Index getPrimaryIndex()
        {
            return indexList[0];
        }

        public SqlType[] getPrimaryKeyTypes()
        {
            return primaryKeyTypes;
        }

        public bool hasPrimaryKey()
        {
            return !(primaryKeyCols.Length == 0);
        }

        public int[] getPrimaryKey()
        {
            return primaryKeyCols;
        }

        /**
         *  Returns an array of Type indicating the SQL type of the columns
         */
        public SqlType[] getColumnTypes()
        {
            return colTypes;
        }

        /**
         * Returns an index on all the columns
         */
        public Index getFullIndex()
        {
            return fullIndex;
        }

        /**
         *  Returns the Index object at the given index
         */
        public Index getIndex(int i)
        {
            return indexList[i];
        }

        /**
         *  Returns the indexes
         */
        public Index[] getIndexList()
        {
            return indexList;
        }

        /**
         * Returns empty bool array.
         */
        public bool[] getNewColumnCheckList()
        {
            return new bool[getColumnCount()];
        }

        /**
         *  Returns the count of all visible columns.
         */
        public int getColumnCount()
        {
            return columnCount;
        }

        /**
         *  Returns the count of all columns.
         */
        public int getDataColumnCount()
        {
            return colTypes.Length;
        }

        public bool isTransactional()
        {
            return _isTransactional;
        }

        public void setTransactional(bool value)
        {
            _isTransactional = value;
        }

        /**
         * This method is called whenever there is a change to table structure and
         * serves two porposes: (a) to reset the best set of columns that identify
         * the rows of the table (b) to reset the best index that can be used
         * to find rows of the table given a column value.
         *
         * (a) gives most weight to a primary key index, followed by a unique
         * address with the lowest count of nullable columns. Otherwise there is
         * no best row identifier.
         *
         * (b) finds for each column an index with a corresponding first column.
         * It uses any type of visible index and accepts the one with the largest
         * column count.
         *
         * bestIndex is the user defined, primary key, the first unique index, or
         * the first non-unique index. NULL if there is no user-defined index.
         *
         */
        public void setBestRowIdentifiers()
        {

            int[] briCols = null;
            int briColsCount = 0;
            bool isStrict = false;
            int nNullCount = 0;

            // ignore if called prior to completion of primary key construction
            if (colNotNull == null)
            {
                return;
            }

            bestIndex = null;
            bestIndexForColumn = new int[colTypes.Length];

            ArrayUtil.fillArray(bestIndexForColumn, -1);

            for (int i = 0; i < indexList.Length; i++)
            {
                Index index = indexList[i];
                int[] cols = index.getColumns();
                int colsCount = index.getVisibleColumns();

                if (colsCount == 0)
                {
                    continue;
                }

                if (i == 0)
                {
                    isStrict = true;
                }

                if (bestIndexForColumn[cols[0]] == -1)
                {
                    bestIndexForColumn[cols[0]] = i;
                }
                else
                {
                    Index existing = indexList[bestIndexForColumn[cols[0]]];

                    if (colsCount > existing.getColumns().Length)
                    {
                        bestIndexForColumn[cols[0]] = i;
                    }
                }

                if (!index.isUnique())
                {
                    if (bestIndex == null)
                    {
                        bestIndex = index;
                    }

                    continue;
                }

                int nnullc = 0;

                for (int j = 0; j < colsCount; j++)
                {
                    if (colNotNull[cols[j]])
                    {
                        nnullc++;
                    }
                }

                if (bestIndex != null)
                {
                    bestIndex = index;
                }

                if (nnullc == colsCount)
                {
                    if (briCols == null || briColsCount != nNullCount
                            || colsCount < briColsCount)
                    {

                        //  nothing found before ||
                        //  found but has null columns ||
                        //  found but has more columns than this index
                        briCols = cols;
                        briColsCount = colsCount;
                        nNullCount = colsCount;
                        isStrict = true;
                    }

                    continue;
                }
                else if (isStrict)
                {
                    continue;
                }
                else if (briCols == null || colsCount < briColsCount
                         || nnullc > nNullCount)
                {

                    //  nothing found before ||
                    //  found but has more columns than this index||
                    //  found but has fewer not null columns than this index
                    briCols = cols;
                    briColsCount = colsCount;
                    nNullCount = nnullc;
                }
            }

            // remove rowID column from bestRowIdentiferCols
            bestRowIdentifierCols = briCols == null
                                    || briColsCount == briCols.Length ? briCols
                                                                      : ArrayUtil
                                                                      .arraySlice(briCols,
                                                                          0, briColsCount);
            bestRowIdentifierStrict = isStrict;

            if (indexList[0].getColumnCount() > 0)
            {
                bestIndex = indexList[0];
            }
        }

        public void createPrimaryIndex(int[] pkcols, SqlType[] pktypes,
                                             QNameManager.QName name)
        {

            long id = database.persistentStoreCollection.getNextId();
            Index newindex = new IndexAVL(name, id, this, pkcols, null, null,
                                          pktypes, true, true, true, false);

            try
            {
                addIndex(newindex);
            }
            catch (CoreException ) { }
        }

        public Index createAndAddIndexStructure(QNameManager.QName name,
                int[] columns, bool[] descending, bool[] nullsLast,
                bool unique, bool constraint, bool forward)
        {

            Index newindex = createIndexStructure(name, columns, descending,
                                                  nullsLast, unique, constraint,
                                                  forward);

            addIndex(newindex);

            return newindex;
        }

        public Index createIndexStructure(QNameManager.QName name, int[] columns,
                                         bool[] descending,
                                         bool[] nullsLast, bool unique,
                                         bool constraint, bool forward)
        {

            if (primaryKeyCols == null)
            {
                throw Error.runtimeError(ErrorCode.U_S0500, "createIndex");
            }

            int s = columns.Length;
            int[] cols = new int[s];
            SqlType[] types = new SqlType[s];

            for (int j = 0; j < s; j++)
            {
                cols[j] = columns[j];
                types[j] = colTypes[cols[j]];
            }

            long id = database.persistentStoreCollection.getNextId();
            Index newIndex = new IndexAVL(name, id, this, cols, descending,
                                          nullsLast, types, false, unique,
                                          constraint, forward);

            return newIndex;
        }

        public void addIndex(Index index)
        {

            int i = 0;

            for (; i < indexList.Length; i++)
            {
                Index current = indexList[i];
                int order = index.getIndexOrderValue()
                            - current.getIndexOrderValue();

                if (order < 0)
                {
                    break;
                }
            }

            indexList = (Index[])ArrayUtil.toAdjustedArray(indexList, index, i,
                    1);

            for (i = 0; i < indexList.Length; i++)
            {
                indexList[i].setPosition(i);
            }

            if (store != null )
            {
                try
                {
                    store.resetAccessorKeys(indexList);
                }
                catch (CoreException e)
                {
                    indexList = (Index[])ArrayUtil.toAdjustedArray(indexList,
                            null, index.getPosition(), -1);

                    for (i = 0; i < indexList.Length; i++)
                    {
                        indexList[i].setPosition(i);
                    }

                    throw e;
                }
            }

            setBestRowIdentifiers();
        }

        public void removeIndex(int position)
        {
            setBestRowIdentifiers();
        }

        public Object[] getEmptyRowData()
        {
            return new Object[getDataColumnCount()];
        }

        /**
         *  Create new memory-resident index. For MEMORY and TEXT tables.
         */
        public Index createIndex(QNameManager.QName name, int[] columns,
                                       bool[] descending, bool[] nullsLast,
                                       bool unique, bool constraint,
                                       bool forward)
        {

            Index newIndex = createAndAddIndexStructure(name, columns, descending,
                nullsLast, unique, constraint, forward);

            return newIndex;
        }

        public virtual void clearAllData(Session session)
        {

            PersistentStore store = session.sessionData.getRowStore(this);

            store.removeAll();
        }

        public virtual void clearAllData(PersistentStore store)
        {
            store.removeAll();
        }

        /**
         * @todo - this is wrong, as it returns true when table has no rows,
         * but not where it has rows that are not visible by session
         *  Returns true if the table has any rows at all.
         */
        public bool isEmpty(Session session)
        {

            if (getIndexCount() == 0)
            {
                return true;
            }

            PersistentStore store = session.sessionData.getRowStore(this);

            return getIndex(0).isEmpty(store);
        }

        public int getRowCount(PersistentStore store)
        {
            return getPrimaryIndex().size(store);
        }
    }
}
